"""
Appium 基础滑动脚本
"""

from appium import webdriver
from appium.options.android import UiAutomator2Options
import time
import argparse

class AppiumSwiper:
    def __init__(self, package, activity):
        self.package = package
        self.activity = activity
        self.driver = None
        
    def connect(self):
        """连接设备并启动应用"""
        options = UiAutomator2Options()
        options.platform_name = "Android"
        options.device_name = "Android"
        options.automation_name = "UiAutomator2"
        options.app_package = self.package
        options.app_activity = self.activity
        options.no_reset = True
        
        appium_server_url = 'http://localhost:4723'
        self.driver = webdriver.Remote(appium_server_url, options=options)
        print("✅ 已连接设备")
        return True
    
    def get_screen_size(self):
        """获取屏幕尺寸"""
        size = self.driver.get_window_size()
        return size['width'], size['height']
    
    def swipe_up(self):
        """向上滑动"""
        width, height = self.get_screen_size()
        
        start_x = width // 2
        start_y = int(height * 0.8)
        end_x = width // 2
        end_y = int(height * 0.2)
        duration = 300
        
        self.driver.swipe(start_x, start_y, end_x, end_y, duration)
        print("✅ 滑动成功")
    
    def run(self, interval=5, count=10):
        """运行自动滑动"""
        if not self.connect():
            return
        
        print(f"⏰ 每 {interval} 秒滑动一次，共 {count} 次")
        print("-" * 50)
        
        try:
            for i in range(count):
                print(f"[{i+1}/{count}] {time.strftime('%H:%M:%S')} ", end="")
                self.swipe_up()
                
                if i < count - 1:
                    time.sleep(interval)
                    
        except KeyboardInterrupt:
            print("\n⏹️  用户停止")
        finally:
            self.driver.quit()
            print("✅ 已断开连接")

def main():
    parser = argparse.ArgumentParser(description='Appium 滑动脚本')
    parser.add_argument('package', help='应用包名')
    parser.add_argument('activity', help='启动 Activity')
    parser.add_argument('-i', '--interval', type=int, default=5,
                       help='滑动间隔（秒）')
    parser.add_argument('-n', '--count', type=int, default=10,
                       help='滑动次数')
    
    args = parser.parse_args()
    
    swiper = AppiumSwiper(args.package, args.activity)
    swiper.run(interval=args.interval, count=args.count)

if __name__ == "__main__":
    main()